'use client';

import { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Textarea } from '@/components/ui/textarea';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { format } from 'date-fns';
import { zhCN } from 'date-fns/locale';
import { Search, Trash2 } from 'lucide-react';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';

interface GenerationRecord {
  id: string;
  serial_number: string;
  software_description: string;
  development_language: string;
  version: string;
  status: string;
  created_at: string;
}

interface TokenUsage {
  id: string;
  request_type: string;
  prompt_tokens?: number;
  completion_tokens?: number;
  total_tokens?: number;
  created_at: string;
}

interface ModelConfig {
  api_url: string;
  api_key: string;
  model_name: string;
}

function getStatusBadgeVariant(status: string) {
  switch (status) {
    case 'summary_generated':
      return 'default';
    case 'full_generated':
      return 'success';
    case 'error':
      return 'destructive';
    default:
      return 'secondary';
  }
}

function getStatusText(status: string) {
  switch (status) {
    case 'summary_generated':
      return '已生成摘要';
    case 'full_generated':
      return '已生成完整内容';
    case 'error':
      return '生成失败';
    default:
      return status;
  }
}

export default function AdminDashboard() {
  const [records, setRecords] = useState<GenerationRecord[]>([]);
  const [tokenStats, setTokenStats] = useState({ today: 0, week: 0, month: 0, year: 0 });
  const [recentTokenUsage, setRecentTokenUsage] = useState<TokenUsage[]>([]);
  const [modelConfigs, setModelConfigs] = useState<Record<string, ModelConfig>>({});
  const [promptTemplates, setPromptTemplates] = useState<Record<string, string>>({});
  const [formData, setFormData] = useState<Record<string, ModelConfig>>({});
  const [promptData, setPromptData] = useState<Record<string, string>>({});
  const [saving, setSaving] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [deleteId, setDeleteId] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchAllData();
  }, []);

  const fetchAllData = async () => {
    try {
      const [recordsRes, statsRes, usageRes, configsRes, promptsRes] = await Promise.all([
        fetch('/api/admin/records').then(r => r.json()),
        fetch('/api/admin/token-stats').then(r => r.json()),
        fetch('/api/admin/token-usage').then(r => r.json()),
        fetch('/api/admin/model-configs').then(r => r.json()),
        fetch('/api/admin/prompt-templates').then(r => r.json())
      ]);

      setRecords(recordsRes.data || []);
      setTokenStats(statsRes.data || { today: 0, week: 0, month: 0, year: 0 });
      setRecentTokenUsage(usageRes.data || []);
      setModelConfigs(configsRes.data || {});
      setFormData(configsRes.data || {});
      setPromptTemplates(promptsRes.data || {});
      setPromptData(promptsRes.data || {});
    } catch (error) {
      console.error('获取数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleModelInputChange = (modelKey: string, field: string, value: string) => {
    setFormData(prev => ({
      ...prev,
      [modelKey]: {
        ...prev[modelKey],
        [field]: value
      }
    }));
  };

  const handlePromptInputChange = (promptKey: string, value: string) => {
    setPromptData(prev => ({
      ...prev,
      [promptKey]: value
    }));
  };

  const savePromptTemplate = async (promptKey: string) => {
    try {
      setSaving(true);
      const response = await fetch('/api/admin/prompt-templates', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          [promptKey]: promptData[promptKey]
        }),
      });
      const data = await response.json();
      if (data.success) {
        // 更新promptTemplates状态
        setPromptTemplates(prev => ({
          ...prev,
          [promptKey]: promptData[promptKey]
        }));
        alert('提示词模板保存成功');
      } else {
        alert(`保存失败: ${data.message || '未知错误'}`);
      }
    } catch (error) {
      console.error('保存提示词模板失败:', error);
      alert('保存提示词模板时发生错误');
    } finally {
      setSaving(false);
    }
  };

  const resetPromptTemplate = (promptKey: string) => {
    // 重置为原始值
    setPromptData(prev => ({
      ...prev,
      [promptKey]: promptTemplates[promptKey]
    }));
  };

  const saveModelConfig = async (modelKey: string) => {
    try {
      setSaving(true);
      const response = await fetch('/api/admin/model-configs', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          [modelKey]: formData[modelKey]
        }),
      });
      const data = await response.json();
      if (data.success) {
        // 更新modelConfigs状态
        setModelConfigs(prev => ({
          ...prev,
          [modelKey]: formData[modelKey]
        }));
        alert('配置保存成功');
      } else {
        alert(`保存失败: ${data.message || '未知错误'}`);
      }
    } catch (error) {
      console.error('保存配置失败:', error);
      alert('保存配置时发生错误');
    } finally {
      setSaving(false);
    }
  };

  const saveAllConfigs = async () => {
    try {
      setSaving(true);
      // 保存所有模型配置
      const modelResponse = await fetch('/api/admin/model-configs', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(formData),
      });
      const modelData = await modelResponse.json();

      // 保存所有提示词模板
      const promptResponse = await fetch('/api/admin/prompt-templates', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(promptData),
      });
      const promptData = await promptResponse.json();

      if (modelData.success && promptData.success) {
        // 更新状态
        setModelConfigs(formData);
        setPromptTemplates(promptResponse.data || {});
        alert('所有配置保存成功');
      } else {
        alert(`保存失败: ${modelData.message || promptData.message || '未知错误'}`);
      }
    } catch (error) {
      console.error('保存所有配置失败:', error);
      alert('保存所有配置时发生错误');
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async (id: string) => {
    try {
      await fetch(`/api/admin/records/${id}`, { method: 'DELETE' });
      setRecords(records.filter(r => r.id !== id));
      setDeleteId(null);
    } catch (error) {
      console.error('删除记录失败:', error);
    }
  };

  const filteredRecords = records.filter(record =>
    record.software_description.toLowerCase().includes(searchTerm.toLowerCase()) ||
    record.serial_number.toLowerCase().includes(searchTerm.toLowerCase()) ||
    record.development_language.toLowerCase().includes(searchTerm.toLowerCase())
  );

  if (loading) {
    return (
      <div className="container mx-auto py-8 px-4">
        <div className="flex justify-center items-center h-64">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
        </div>
      </div>
    );
  }

  return (
    <div className="container mx-auto py-8 px-4">
      <div className="mb-8">
        <h1 className="text-3xl font-bold mb-2">管理后台</h1>
        <p className="text-muted-foreground">软件著作权申请管理系统</p>
      </div>

      <Tabs defaultValue="overview" className="space-y-4">
        <TabsList>
          <TabsTrigger value="overview">总览</TabsTrigger>
          <TabsTrigger value="tokens">Token统计</TabsTrigger>
          <TabsTrigger value="models">模型配置</TabsTrigger>
          <TabsTrigger value="prompts">提示词管理</TabsTrigger>
        </TabsList>

        <TabsContent value="overview" className="space-y-4">
          <div className="grid gap-6">
            <Card>
              <CardHeader>
                <CardTitle>生成记录统计</CardTitle>
                <CardDescription>最近50条生成记录</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  <div className="p-4 bg-muted rounded-lg">
                    <div className="text-2xl font-bold">{records.length}</div>
                    <div className="text-sm text-muted-foreground">总记录数</div>
                  </div>
                  <div className="p-4 bg-green-50 rounded-lg">
                    <div className="text-2xl font-bold text-green-600">
                      {records.filter(r => r.status === 'full_generated').length}
                    </div>
                    <div className="text-sm text-muted-foreground">已完成</div>
                  </div>
                  <div className="p-4 bg-red-50 rounded-lg">
                    <div className="text-2xl font-bold text-red-600">
                      {records.filter(r => r.status === 'error').length}
                    </div>
                    <div className="text-sm text-muted-foreground">失败</div>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>生成记录列表</CardTitle>
                <CardDescription>按创建时间倒序排列</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="overflow-x-auto">
                  <div className="flex gap-2 mb-4">
                    <div className="relative flex-1">
                      <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
                      <Input
                        placeholder="搜索记录..."
                        value={searchTerm}
                        onChange={(e) => setSearchTerm(e.target.value)}
                        className="pl-8"
                      />
                    </div>
                  </div>
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>序列号</TableHead>
                        <TableHead>软件描述</TableHead>
                        <TableHead>开发语言</TableHead>
                        <TableHead>版本</TableHead>
                        <TableHead>状态</TableHead>
                        <TableHead>创建时间</TableHead>
                        <TableHead>操作</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {filteredRecords.length === 0 ? (
                        <TableRow>
                          <TableCell colSpan={7} className="text-center py-8">
                            暂无生成记录
                          </TableCell>
                        </TableRow>
                      ) : (
                        filteredRecords.map((record) => (
                          <TableRow key={record.id}>
                            <TableCell className="font-mono text-sm">
                              {record.serial_number}
                            </TableCell>
                            <TableCell className="max-w-xs truncate">
                              {record.software_description}
                            </TableCell>
                            <TableCell>{record.development_language}</TableCell>
                            <TableCell>{record.version}</TableCell>
                            <TableCell>
                              <Badge variant={getStatusBadgeVariant(record.status)}>
                                {getStatusText(record.status)}
                              </Badge>
                            </TableCell>
                            <TableCell>
                              {format(new Date(record.created_at), 'yyyy-MM-dd HH:mm', { locale: zhCN })}
                            </TableCell>
                            <TableCell>
                              <Button
                                variant="ghost"
                                size="sm"
                                onClick={() => setDeleteId(record.id)}
                              >
                                <Trash2 className="h-4 w-4" />
                              </Button>
                            </TableCell>
                          </TableRow>
                        ))
                      )}
                    </TableBody>
                  </Table>
                </div>
              </CardContent>
            </Card>
          </div>
        </TabsContent>

        <TabsContent value="tokens" className="space-y-4">
          <div className="grid gap-6">
            <Card>
              <CardHeader>
                <CardTitle>Token消耗统计</CardTitle>
                <CardDescription>实时统计各时间段token消耗</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                  <div className="p-4 bg-blue-50 rounded-lg">
                    <div className="text-2xl font-bold text-blue-600">{tokenStats.today.toLocaleString()}</div>
                    <div className="text-sm text-muted-foreground">今日消耗</div>
                  </div>
                  <div className="p-4 bg-green-50 rounded-lg">
                    <div className="text-2xl font-bold text-green-600">{tokenStats.week.toLocaleString()}</div>
                    <div className="text-sm text-muted-foreground">本周消耗</div>
                  </div>
                  <div className="p-4 bg-purple-50 rounded-lg">
                    <div className="text-2xl font-bold text-purple-600">{tokenStats.month.toLocaleString()}</div>
                    <div className="text-sm text-muted-foreground">本月消耗</div>
                  </div>
                  <div className="p-4 bg-orange-50 rounded-lg">
                    <div className="text-2xl font-bold text-orange-600">{tokenStats.year.toLocaleString()}</div>
                    <div className="text-sm text-muted-foreground">年度消耗</div>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>最近Token使用记录</CardTitle>
                <CardDescription>最近10条包含token消耗的记录</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="overflow-x-auto">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>请求类型</TableHead>
                        <TableHead>Prompt Tokens</TableHead>
                        <TableHead>Completion Tokens</TableHead>
                        <TableHead>总 Tokens</TableHead>
                        <TableHead>时间</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {recentTokenUsage.length === 0 ? (
                        <TableRow>
                          <TableCell colSpan={5} className="text-center py-8">
                            暂无Token使用记录
                          </TableCell>
                        </TableRow>
                      ) : (
                        recentTokenUsage.map((usage) => (
                          <TableRow key={usage.id}>
                            <TableCell>{usage.request_type}</TableCell>
                            <TableCell>{usage.prompt_tokens?.toLocaleString() || 0}</TableCell>
                            <TableCell>{usage.completion_tokens?.toLocaleString() || 0}</TableCell>
                            <TableCell>{usage.total_tokens?.toLocaleString() || 0}</TableCell>
                            <TableCell>
                              {format(new Date(usage.created_at), 'yyyy-MM-dd HH:mm', { locale: zhCN })}
                            </TableCell>
                          </TableRow>
                        ))
                      )}
                    </TableBody>
                  </Table>
                </div>
              </CardContent>
            </Card>
          </div>
        </TabsContent>

        <TabsContent value="models" className="space-y-4">
          <div className="mb-4 flex justify-end">
            <Button
              onClick={saveAllConfigs}
              disabled={saving}
              className="bg-primary text-white"
            >
              {saving ? '保存中...' : '一键保存全部配置'}
            </Button>
          </div>
          <div className="grid gap-6">
            {Object.entries(modelConfigs).map(([key, config]) => (
              <Card key={key}>
                <CardHeader>
                  <CardTitle>
                    {key === 'model_for_form' && '登记申请表模型配置'}
                    {key === 'model_for_code' && '源程序模型配置'}
                    {key === 'model_for_document' && '说明文档模型配置'}
                    {key === 'model_for_prompt_expert' && '提示词优化专家模型配置'}
                  </CardTitle>
                  <CardDescription>
                    {key === 'model_for_prompt_expert' ? '配置用于生成和优化提示词的专家模型API参数' : '配置对应模块的API调用参数'}
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="space-y-4">
                    <div>
                      <Label htmlFor={`${key}-api_url`}>API URL</Label>
                      <Input
                        id={`${key}-api_url`}
                        name="api_url"
                        type="url"
                        value={formData[key]?.api_url || ''}
                        onChange={(e) => handleModelInputChange(key, 'api_url', e.target.value)}
                        placeholder="https://open.bigmodel.cn/api/paas/v4/chat/completions"
                      />
                    </div>
                    <div>
                      <Label htmlFor={`${key}-api_key`}>API Key</Label>
                      <Input
                        id={`${key}-api_key`}
                        name="api_key"
                        type="password"
                        value={formData[key]?.api_key || ''}
                        onChange={(e) => handleModelInputChange(key, 'api_key', e.target.value)}
                        placeholder="请输入API密钥"
                      />
                    </div>
                    <div>
                      <Label htmlFor={`${key}-model_name`}>模型名称</Label>
                      <Input
                        id={`${key}-model_name`}
                        name="model_name"
                        value={formData[key]?.model_name || ''}
                        onChange={(e) => handleModelInputChange(key, 'model_name', e.target.value)}
                        placeholder="glm-4"
                      />
                    </div>
                    <Button
                      onClick={() => saveModelConfig(key)}
                      disabled={saving}
                      className="w-full md:w-auto"
                    >
                      {saving ? '保存中...' : '保存配置'}
                    </Button>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        </TabsContent>

        <TabsContent value="prompts" className="space-y-4">
          <div className="mb-4 flex justify-end">
            <Button
              onClick={saveAllConfigs}
              disabled={saving}
              className="bg-primary text-white"
            >
              {saving ? '保存中...' : '一键保存全部配置'}
            </Button>
          </div>
          <div className="grid gap-6">
            <Card>
              <CardHeader>
                <CardTitle>提示词模板管理</CardTitle>
                <CardDescription>管理各阶段的提示词模板</CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                {Object.entries(promptTemplates).map(([key, template]) => (
                  <div key={key} className="space-y-2">
                    <Label className="font-semibold">{key}</Label>
                    <Textarea
                      value={promptData[key] || ''}
                      rows={3}
                      onChange={(e) => handlePromptInputChange(key, e.target.value)}
                      className="font-mono text-sm"
                    />
                    <div className="flex gap-2">
                      <Button size="sm" onClick={() => savePromptTemplate(key)} disabled={saving}>
                        {saving ? '保存中...' : '保存'}
                      </Button>
                      <Button size="sm" variant="outline" onClick={() => resetPromptTemplate(key)}>
                        重置
                      </Button>
                    </div>
                  </div>
                ))}
              </CardContent>
            </Card>
          </div>
        </TabsContent>
      </Tabs>

      <AlertDialog open={!!deleteId} onOpenChange={() => setDeleteId(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>确认删除</AlertDialogTitle>
            <AlertDialogDescription>
              确定要删除这条生成记录吗？此操作无法撤销。
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>取消</AlertDialogCancel>
            <AlertDialogAction
              onClick={() => deleteId && handleDelete(deleteId)}
              className="bg-destructive text-destructive-foreground"
            >
              删除
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}